from django.shortcuts import render, redirect
from web import models
from web.utils.pagination import Pagination
from django import forms
from django.core.exceptions import ValidationError
from web.utils.bootstrip import BootstrapModelForm
from web.utils.encrypt import md5


def admin_list(request):
    """管理员列表"""

    # 构造搜索条件
    data_dic = {}
    search_data = request.GET.get('user', '')
    if search_data:
        data_dic["username__contains"] = search_data
    # 根据搜索条件去数据库获取数据
    queryset = models.Admin.objects.filter(**data_dic)
    # 分页
    page_object = Pagination(request, queryset)
    context = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.html()
    }
    return render(request, 'admin_list.html', context)


class AdminModelForm(BootstrapModelForm):
    confirm_password = forms.CharField(label="确认密码", widget=forms.PasswordInput(render_value=True))

    class Meta:
        model = models.Admin
        fields = ["username", "password", "confirm_password"]
        widgets = {
            "password": forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)

    def clean_confirm_password(self):
        pwd = self.cleaned_data.get("password")
        # 因为 密码是 加密后的字符串，所以 确认密码 也要进行加密
        confirm = md5(self.cleaned_data.get("confirm_password"))
        if confirm != pwd:
            raise ValidationError("密码不一致")
        # 返回什么，此字段以后保存到数据库就是什么。
        return confirm


def admin_add(request):
    """新建管理员"""
    title = '新建管理员'
    if request.method == "GET":
        form = AdminModelForm()
        return render(request, 'change.html', {'form': form, 'title': title})
    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')

    return render(request, 'change.html', {'form': form, 'title': title})


class AdminEditModelForm(BootstrapModelForm):
    class Meta:
        model = models.Admin
        fields = ['username']


def admin_edit(request, nid):
    """编辑管理员"""
    # 获取当前行 对象,如果不存在，则是None
    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        return redirect('/admin/list/')
        # 当前编辑行不存在，也可以让其跳到一自定义的错误页面
        # return render(request, 'error.html', {'msg': '数据不存在'})

    title = '编辑管理员'

    if request.method == "GET":
        form = AdminEditModelForm(instance=row_object)  # instance=row_object 表示显示页面默认值
        return render(request, 'change.html', {'form': form, 'title': title})

    form = AdminEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')

    return render(request, 'change.html', {'form': form, 'title': title})


def admin_delete(request, nid):
    """删除管理员"""
    models.Admin.objects.filter(id=nid).delete()
    return redirect('/admin/list/')


class AdminResetModelForm(BootstrapModelForm):
    confirm_password = forms.CharField(label="确认密码", widget=forms.PasswordInput(render_value=True))

    class Meta:
        model = models.Admin
        fields = ['password', 'confirm_password']
        widgets = {
            'password': forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        md5_pwd = md5(pwd)

        # 去数据库校验，当前输入的密码和原密码要不一致
        exists = models.Admin.objects.filter(id=self.instance.pk, password=md5_pwd).exists()
        if exists:
            raise ValidationError("输入密码不能和原密码一致")
        return md5_pwd

    def clean_confirm_password(self):
        pwd = self.cleaned_data.get("password")
        # 因为 密码是 加密后的字符串，所以 确认密码 也要进行加密
        confirm = md5(self.cleaned_data.get("confirm_password"))
        if confirm != pwd:
            raise ValidationError("密码不一致")
        # 返回什么，此字段以后保存到数据库就是什么。
        return confirm


def admin_reset(request, nid):
    """重置密码"""
    # 对象/ None
    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        return redirect('/admin/list/')

    title = '重置密码 - {}'.format(row_object.username)
    if request.method == "GET":
        form = AdminResetModelForm()
        return render(request, 'change.html', {'form': form, 'title': title})

    form = AdminResetModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'change.html', {'form': form, 'title': title})
